<template>
  <div class="workflow-execute-result">
    <!-- 执行控制 -->
    <el-button 
      v-if="componentType === 'execute-button'"
      type="primary" 
      @click="executeWorkflow" 
      :loading="isExecuting"
      :disabled="!isWorkflowValid"
    >
      {{ isExecuting ? '执行中...' : '执行流程' }}
    </el-button>

    <!-- 进度展示 -->
    <div v-if="isExecuting" class="progress-container">
      <el-progress :percentage="executionProgress" :stroke-width="15" striped />
      <p>{{ currentStatusText }}</p>
    </div>

    <!-- 结果预览 -->
    <CommonModal :visible="resultVisible" title="结果预览" @close="resultVisible = false" width="70%">
      <div v-if="currentResult">
        <!-- 可视化结果 -->
        <div v-if="currentResult.type === 'chart'" ref="chartContainer" style="width: 100%; height: 400px;"></div>
        <!-- 数据类结果 -->
        <el-table v-if="currentResult.type === 'table'" :data="currentResult.data" border height="400">
           <el-table-column v-for="col in currentResult.columns" :key="col" :prop="col" :label="col"></el-table-column>
        </el-table>
      </div>
    </CommonModal>

    <!-- 执行日志 -->
     <CommonModal :visible="logVisible" title="执行日志" @close="logVisible = false" width="60%">
        <el-table :data="logs" height="400" border>
            <el-table-column prop="time" label="时间" width="180"></el-table-column>
            <el-table-column prop="node" label="节点"></el-table-column>
            <el-table-column prop="message" label="信息"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                    <el-tag :type="scope.row.status === '成功' ? 'success' : 'danger'">{{ scope.row.status }}</el-tag>
                </template>
            </el-table-column>
        </el-table>
     </CommonModal>
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue';
import { useWorkflowStore } from '../../stores/workflow';
import { ElMessage, ElMessageBox } from 'element-plus';
import CommonModal from '../common/CommonModal.vue';
import * as echarts from 'echarts';

const props = defineProps({
  componentType: {
    type: String,
    required: true,
    default: 'execute-button' // or 'result-preview', 'log-viewer'
  }
});

const workflowStore = useWorkflowStore();
const isExecuting = ref(false);
const executionProgress = ref(0);
const currentStatusText = ref('');
const resultVisible = ref(false);
const logVisible = ref(false);
const currentResult = ref(null);
const logs = ref([]);
const chartContainer = ref(null);

const isWorkflowValid = computed(() => {
  const data = workflowStore.workflowData;
  return data && data.nodeDataArray?.length > 0 && data.linkDataArray?.length > 0;
});

const executeWorkflow = async () => {
  if (!isWorkflowValid.value) {
    ElMessage.warning('工作流不完整，无法执行');
    return;
  }

  isExecuting.value = true;
  executionProgress.value = 0;
  logs.value = [];

  const nodes = workflowStore.workflowData.nodeDataArray;
  const links = workflowStore.workflowData.linkDataArray;
  
  // 简单的拓扑排序
  const sortedNodes = [];
  const inDegree = {};
  nodes.forEach(n => inDegree[n.key] = 0);
  links.forEach(l => inDegree[l.to]++);
  
  const queue = nodes.filter(n => inDegree[n.key] === 0);

  while(queue.length > 0) {
      const node = queue.shift();
      sortedNodes.push(node);
      links.filter(l => l.from === node.key).forEach(l => {
          inDegree[l.to]--;
          if(inDegree[l.to] === 0) {
              queue.push(nodes.find(n => n.key === l.to));
          }
      });
  }

  for (let i = 0; i < sortedNodes.length; i++) {
    const node = sortedNodes[i];
    currentStatusText.value = `正在执行: ${node.text} (${i+1}/${sortedNodes.length})`;
    addLog(node.text, '开始执行', '成功');
    
    // 模拟执行耗时
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 模拟成功或失败
    if (Math.random() < 0.1) {
      addLog(node.text, '执行失败', '失败');
      ElMessage.error(`${node.text} 执行失败`);
      isExecuting.value = false;
      return;
    }
    
    addLog(node.text, '执行成功', '成功');
    executionProgress.value = Math.round(((i + 1) / sortedNodes.length) * 100);

    // 模拟结果预览
    if (node.text === '结果预览') {
        previewResult(node);
    }
  }

  currentStatusText.value = '工作流执行完毕';
  isExecuting.value = false;
  ElMessage.success('工作流执行完毕');
  logVisible.value = true; // 执行完自动显示日志
};

const addLog = (node, message, status) => {
    logs.value.push({ time: new Date().toLocaleString(), node, message, status });
};

const previewResult = (node) => {
    // 模拟生成结果
    if(node.text.includes('降维')) {
        currentResult.value = {
            type: 'chart',
            data: {
                xAxis: { type: 'value' },
                yAxis: { type: 'value' },
                series: [{
                    symbolSize: 10,
                    data: Array(100).fill(0).map(() => [Math.random()*10, Math.random()*10]),
                    type: 'scatter'
                }]
            }
        };
        resultVisible.value = true;
        nextTick(() => {
            const chart = echarts.init(chartContainer.value);
            chart.setOption(currentResult.value.data);
        });
    } else {
         currentResult.value = {
            type: 'table',
            columns: ['ID', 'Value1', 'Value2'],
            data: Array(20).fill(0).map((_, i) => ({ ID: `Sample${i+1}`, Value1: Math.random(), Value2: Math.random() }))
         };
         resultVisible.value = true;
    }
};
</script>

<style scoped>
.progress-container {
  margin-top: 10px;
  text-align: center;
}
</style>
